package com.feilong.edgeAI.speech;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.feilong.edgeAI.model.AINetRespone;
import com.feilong.edgeAI.model.RouseRespone;
import com.feilong.edgeAI.speech.util.AbilityConstant;
import com.google.gson.Gson;
import com.iflytek.aikit.core.AiAudio;
import com.iflytek.aikit.core.AiHandle;
import com.iflytek.aikit.core.AiHelper;
import com.iflytek.aikit.core.AiListener;
import com.iflytek.aikit.core.AiRequest;
import com.iflytek.aikit.core.AiResponse;
import com.iflytek.aikit.core.AiStatus;
import com.iflytek.aikit.core.DataStatus;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2023/11/14 14:11
 */
public class IvwHelper implements AiListener, RecordeHelper.RecordListener {
    private static final String TAG = "feilongedgeAI";
    private IvwHelperListener ivwHelperListener;
    private AiHandle handleWake;
    public static AiStatus ivwAiStatus = AiStatus.BEGIN;
    private EdHelper edHelper;
    public static boolean edState;
    private Context context;

    @SuppressLint("LongLogTag")
    public IvwHelper(Context context, EdHelper edHelper) {
        this.context = context;
        this.edHelper = edHelper;
        String ssid = NetworkUtils.getSSID();
        Log.d(TAG, "IvwHelper: ssid=" + ssid);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "IvwHelper: NetworkUtils.isAvailable()=" + NetworkUtils.isAvailable());
            }
        }).start();
        Log.d(TAG, "IvwHelper: RecordeHelperisRecording=" + RecordeHelper.isRecording);
        AiHelper.getInst().registerListener(AbilityConstant.IVW_ID, this);
        recordeHelper = new RecordeHelper();
        recordeHelper.createAudioRecord();
        recordeHelper.setRecordListener(this);
    }

    private RecordeHelper recordeHelper;

    /**
     * 启动录音
     */
    public void startRecord() {
//        if(!RecordeHelper.isRecording){
        recordeHelper.startRecord();
//        }
    }

    public void resumeRecord() {
        edStatus = AiStatus.BEGIN;

//        if(!RecordeHelper.isRecording){
        recordeHelper.startRecord();
//        }
    }

    public void pauseRecord() {
        edStatus = AiStatus.END;
//        if(!RecordeHelper.isRecording){
//            recordeHelper.pasueRecord();
//        }
    }

    private String keyword;
    private List<String> keywordList;

    /**
     * 唤醒词路径
     *
     * @return
     */
    public static String getKeyPath() {
        String WORK_DIR = AbilityInit.IFLYTEK_ROOT + File.separator + "ivw";
        return WORK_DIR + File.separator + "keyword.txt";
    }

    public void initCustom() {
        AiRequest.Builder customBuilder = AiRequest.builder();
//key：数据标识 value： 唤醒词配置文件 index： 数据索引,用户可自定义设置
        String keytxt = getKeyPath();
        customBuilder.customText("key_word", keytxt, 0);
        File file = new File(keytxt);
        Log.d(TAG, "IvwHelper startIvw: file=" + file.getAbsolutePath());
        if (!file.exists()) {
            Toast.makeText(context, "缺少语音文件", Toast.LENGTH_LONG).show();
            return;
        }
        keyword = FileIOUtils.readFile2String(getKeyPath(), "utf-8");
//        if(keyword.contains("\r\n")){
//            keyword = keyword.substring(0,keyword.indexOf("\r\n"));
//        }
//        keyword.replaceAll("\r\n","").replaceAll(" ","");
        String[] items = keyword.split(";");
        if (items.length > 0) {
            keywordList = new ArrayList<>();
            for (String temp : items) {
                temp = temp.replaceAll("\n", "").replaceAll(" ", "");
                keywordList.add(temp);
            }
        }

        Log.d(TAG, "IvwHelper startIvw: keyword=" + keyword);
        int ret = AiHelper.getInst().loadData(AbilityConstant.IVW_ID, customBuilder.build());
        if (ret != 0) {
            Log.e(TAG, "IvwHelper loadData 失败：" + ret);
        }
//指定要使用的个性化数据集合，未调用，则默认使用所有loadData加载的数据

        int[] indexs = {0};
        /*
         * indexs 个性化数据索引数组
         */
        int rr = AiHelper.getInst().specifyDataSet(AbilityConstant.IVW_ID, "key_word", indexs);
        if (rr != 0) {
            Log.e(TAG, "IvwHelper specifyDataSet 失败：" + rr);
        }
    }

    /**
     * 启动唤醒
     */
    public void startIvw() {
        initCustom();
        int engineInit = AiHelper.getInst().engineInitNoParams(AbilityConstant.IVW_ID);
        if (engineInit != 0) {
            String str = "engineInit Failed!" + engineInit;
            Log.e(TAG, str);
        } else {
//            engineInit = true;
        }
        endWake = false;
        edState = false;
        AiRequest.Builder paramBuilder = AiRequest.builder();
        paramBuilder.param("wdec_param_nCmThreshold", "0 0:700");
        paramBuilder.param("gramLoad", true);
        handleWake = AiHelper.getInst().start(AbilityConstant.IVW_ID, paramBuilder.build(), null);
//        Log.d(TAG, "startIvw: handleWake.isSuccess="+handleWake.isSuccess());
        if (!handleWake.isSuccess()) {
            if (null != onIvwErrorListener) {
                onIvwErrorListener.onIvwError();
            }
            if (handleWake.getCode() == 18310) {
//                stopIvw();
//                startIvw();
            }
            Log.e(TAG, "IvwHelper ERROR::START | handle code:" + handleWake.getCode());
            return;
        }
        ivwAiStatus = AiStatus.BEGIN;
//        startRecord();

    }

    private OnIvwErrorListener onIvwErrorListener;

    public void setOnIvwErrorListener(OnIvwErrorListener onIvwErrorListener) {
        this.onIvwErrorListener = onIvwErrorListener;
    }

    public interface OnIvwErrorListener {
        void onIvwError();
    }

    private boolean endWake;

    public void startEd() {
        Log.d(TAG, "IvwHelper startEd: ");
        edHelper.startRec();
    }

    /**
     * 查询识别的状态
     *
     * @return
     */
    public boolean getEDState() {
        return this.edState;
    }

    public void stopEd() {
        Log.d(TAG, "IvwHelper stopEd: ");
        if (edState) {
            edStatus = AiStatus.END;
            edHelper.endAiHandle();
        }
        edState = false;
//        recordeHelper.stopRecord();
    }

    public void stopIvw() {
        edState = false;
        endWake = true;
        end();
    }

    /**
     * 唤醒结果
     *
     * @param handleID
     * @param outputData
     * @param o
     */
    @Override
    public void onResult(int handleID, List<AiResponse> outputData, Object o) {
        if (null != outputData && outputData.size() > 0) {
            String result = "";
            for (int i = 0; i < outputData.size(); i++) {
                byte[] bytes = outputData.get(i).getValue();
                try {
                    result = ProgramAnaly(bytes);
//                    Log.d(TAG, "IvwHelper onResult: ss-----"+result);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (bytes == null) {
                    continue;
                }
                boolean online = false;
                boolean check = false;
//                boolean online = NetworkUtil.isNetworkAvailable(context);
                for (String temp : keywordList) {
                    if (result.contains(temp)) {
                        check = true;
                        break;
                    }
                }
                if (null != ivwHelperListener && keywordList.size() > 0 && check) {
                    if (result != null) {
                        Gson gson = new Gson();
                        RouseRespone rouse = gson.fromJson(result, RouseRespone.class);
                        if(rouse!=null&&rouse.rlt!=null&&rouse.rlt.size()>0){
                            if(rouse.rlt.get(0).keyword.equals("小飞小飞")){
                                online=true;
                            }else{
                                online=false;
                            }
                        }
                    }
                    ivwHelperListener.onWakeup(online);
                }

                String key = outputData.get(i).getKey();
                Log.d(TAG, "IvwHelper onResult: " + key);
                //获取到结果的key及value，可根据业务保存存储结果或其他处理
            }
        }
    }

    private String ProgramAnaly(byte[] buf) throws UnsupportedEncodingException {
        byte[] vsnFileByte = new byte[buf.length];
        System.arraycopy(buf, 0, vsnFileByte, 0, buf.length);
        return new String(vsnFileByte, "UTF-8");
    }

    @Override
    public void onEvent(int i, int i1, List<AiResponse> list, Object o) {
        Log.e(TAG, "IvwHelper onEvent: event=" + i);
    }

    @Override
    public void onError(int i, int i1, String s, Object o) {

    }

    public void setIvwHelperListener(IvwHelperListener ivwHelperListener) {
        this.ivwHelperListener = ivwHelperListener;
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {

    }

    @Override
    public void onVolume(int volume) {
        if (null != ivwHelperListener) {
            ivwHelperListener.onVolume(volume, edState);
        }
    }

    @Override
    public void onRecording(byte[] buffer) {
//        Log.d(TAG, "onRecording: length="+buffer.length);
//        Log.d(TAG, "onRecording: edState="+edState);
        if (edState) {//进入识别状态
            edHelper.write(buffer, edStatus);
            if (edStatus == AiStatus.BEGIN) {
                edStatus = AiStatus.CONTINUE;
            }
        }
//        else{
//        Log.d(TAG, "onRecording: "+aiStatus.name());
//            if(aiStatus==AiStatus.END){
//                return;
//            }
        writeAudiowake(buffer, ivwAiStatus);//持续唤醒
        if (ivwAiStatus == AiStatus.BEGIN) {
            ivwAiStatus = AiStatus.CONTINUE;
        }
//        }
    }

    public static AiStatus edStatus;

    public interface IvwHelperListener {
        void onWakeup(boolean online);

        void onVolume(int volume, boolean recognition);
    }

    private void writeAudiowake(byte[] buffer, AiStatus aiStatus) {
//        Log.d(TAG, "writeAudiowake: buffer="+buffer.length+" endWake="+endWake+" aiStatus="+aiStatus.name());
        AiRequest.Builder dataBuilder = AiRequest.builder();
//输入音频数据
        AiAudio.Holder wavData = AiAudio
                .get("wav")//输入数据key
                .encoding(AiAudio.ENCODING_DEFAULT)//设置音频类型
                .data(buffer);//part为 byte[]类型输入数据
//        dataBuilder.audio("wav", buffer);
        wavData.status(aiStatus); //送入数据的状态，首帧数据、尾帧数据、中间数据，根据送入数据的状态传入对应的值，取值对应AiStatus.BEGIN、AiStatus.END、AiStatus.CONTINUE

        dataBuilder.payload(wavData.valid());

        int ret = AiHelper.getInst().write(dataBuilder.build(), handleWake);
//ret 值为0 写入成功；非0失败，请参照文档中错误码部分排查

        if (ret != 0) {
            String error = "write-failed" + ret + " ivwAiStatus=" + aiStatus.name();
//            Log.e(TAG, error);
        } else {
//            Log.d(TAG, "writeAudiowake:write_ret= "+ret);
        }
    }

    /**
     * 停止唤醒
     */
    private void end() {
        ivwAiStatus = AiStatus.END;
        RecordeHelper.isRecording = false;
        int ret = AiHelper.getInst().end(handleWake);
        Log.e(TAG, "IvwHelper end: ret=" + ret);
        if (ret != 0) {
            String error = "IvwHelper end failed" + ret;
            Log.e(TAG, error);
        }
//        recordeHelper.pasueRecord();
        recordeHelper.stopRecord();
    }
}
